package com.easilyj.controller.manage;

import com.easilyj.bean.ArticleCategory;
import com.easilyj.constant.RoleConstant;
import com.easilyj.service.ArticleCategoryService;
import com.easilyj.util.ResponseResult;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class ManageArticleCategoryController {

    @Resource
    private ArticleCategoryService articleCategoryService;

    // 删除
    @GetMapping("/manage/article/category/delete/{id}")
    @RequiresRoles(RoleConstant.ROLE_ADMIN)
    @ResponseBody
    public Object delete(@PathVariable Long id) {
        try {
            articleCategoryService.deleteById(id);
            return new ResponseResult(200, "删除成功", null);
        } catch (Exception e) {
            return new ResponseResult(100, "删除失败", null);
        }
    }

    // 预新增
    @GetMapping("/manage/article/category/add")
    @RequiresRoles(RoleConstant.ROLE_ADMIN)
    public String add() {
        return "manage/manage-ac-add";
    }

    // 新增
    @PostMapping("/manage/article/category/add")
    @RequiresRoles(RoleConstant.ROLE_ADMIN)
    @ResponseBody
    public Object add(ArticleCategory ac) {
        ArticleCategory articleCategory = articleCategoryService.save(ac);
        if (articleCategory != null) {
            return new ResponseResult(200, "新增成功", articleCategory);
        }
        return new ResponseResult(100, "新增失败", null);
    }

    // 预更新
    @GetMapping("/manage/article/category/get/{id}")
    @RequiresRoles(RoleConstant.ROLE_ADMIN)
    public String get(@PathVariable Long id, Model model) {
        ArticleCategory articleCategory = articleCategoryService.getOne(id);
        model.addAttribute("articleCategory", articleCategory);
        return "manage/manage-ac-update";
    }

    // 更新
    @PostMapping("/manage/article/category/update")
    @RequiresRoles(RoleConstant.ROLE_ADMIN)
    @ResponseBody
    public Object update(ArticleCategory ac) {
        ArticleCategory articleCategory = articleCategoryService.save(ac);
        if (articleCategory != null) {
            return new ResponseResult(200, "更新成功", articleCategory);
        }
        return new ResponseResult(100, "更新失败", null);
    }

    // 分类列表
    @GetMapping("/manage/article/category/list")
    @RequiresRoles(RoleConstant.ROLE_ADMIN)
    public String list(Model model) {
        List<ArticleCategory> articleCategoryList = articleCategoryService.findAll();
        model.addAttribute("articleCategoryList", articleCategoryList);
        return "manage/manage-ac";
    }
}
